from builtins import range
import numpy as np
from random import shuffle
from past.builtins import xrange

def softmax_loss_naive(W, X, y, reg):
    """
    Softmax loss function, naive implementation (with loops)

    Inputs have dimension D, there are C classes, and we operate on minibatches
    of N examples.

    Inputs:
    - W: A numpy array of shape (D, C) containing weights.
    - X: A numpy array of shape (N, D) containing a minibatch of data.
    - y: A numpy array of shape (N,) containing training labels; y[i] = c means
      that X[i] has label c, where 0 <= c < C.
    - reg: (float) regularization strength

    Returns a tuple of:
    - loss as single float
    - gradient with respect to weights W; an array of same shape as W
    """
    # Initialize the loss and gradient to zero.
    loss = 0.0
    dW = np.zeros_like(W)

    #############################################################################
    # TODO: Compute the softmax loss and its gradient using explicit loops.     #
    # Store the loss in loss and the gradient in dW. If you are not careful     #
    # here, it is easy to run into numeric instability. Don't forget the        #
    # regularization!                                                           #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    (N, D) = X.shape
    C = W.shape[1]
    for i in range(N):
        scores = X[i].dot(W)
        scores = scores - np.max(scores)
        current_score = np.exp(scores[y[i]])
        m_sum = np.sum(np.exp(scores))
        loss += np.log(m_sum) - np.log(current_score)
        for j in xrange(C):
            if j == y[i]:
                dW[:, j] += np.exp(scores[j]) / m_sum * X[i] - X[i]
            else:
                dW[:, j] += np.exp(scores[j]) / m_sum * X[i]
    loss /= N
    loss += reg * np.sum(W*W)
    dW /= N
    dW += 2 * reg * W

    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    return loss, dW


def softmax_loss_vectorized(W, X, y, reg):
    """
    Softmax loss function, vectorized version.

    Inputs and outputs are the same as softmax_loss_naive.
    """
    # Initialize the loss and gradient to zero.
    loss = 0.0
    dW = np.zeros_like(W)

    #############################################################################
    # TODO: Compute the softmax loss and its gradient using no explicit loops.  #
    # Store the loss in loss and the gradient in dW. If you are not careful     #
    # here, it is easy to run into numeric instability. Don't forget the        #
    # regularization!                                                           #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    (N, D) = X.shape
    C = W.shape[1]
    scores = X.dot(W)
    scores -= np.max(scores, axis = 1, keepdims=True)
    current_score = np.sum(scores[range(N),y])
    scores = np.exp(scores)
    scores_sum = np.sum(scores, axis = 1)

    loss = -current_score + np.sum(np.log(scores_sum))
    loss = loss / N + reg * np.sum(W*W)

    # #根据公式 softmax求导的公式，分类讨论。

    prob = scores / scores_sum
    #print(prob.shape) #（500，10）
    prob[range(N), y] -= 1    #把 -Xi 项“分配”进梯度的公式里 因为j=Yi时候，dW的结果有一项-Xi

    #print(X.shape) #(500, 3073)
    dW = np.dot(X.T, prob)
    dW = dW / N + 2 * reg * W

    #*****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    return loss, dW
